# yun-cha-coffee PyCharm
# userAddress Y
# 2025/8/30 下午4:51
from fastapi import APIRouter, HTTPException, status,Request
from typing import List, Optional

from app.dependencies import get_current_user
from app.models import *
from pydantic import BaseModel, validator, Field
from datetime import datetime
from fastapi import Depends, HTTPException, Header
userAddress_api = APIRouter(prefix="/userAddress")

async def get_current_user_id(request: Request) -> int:
    """
    从Session中获取当前用户ID
    """
    user_id = request.session.get("user_id")
    if not user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="请先登录"
        )
    return user_id

@userAddress_api.get("/{user_id}",summary="查询我的所有地址")
async def getAllMyAddresses(user_id: int):
    # 查询所有用户地址
    addresses = await UserAddress.filter(user_id=user_id).order_by("-is_default", "-created_at")
    return {
        "code": 200,
        "message": "查询成功",
        "data": addresses
    }


@userAddress_api.get("/one/{address_id}",summary="查询一条地址的详情")
async def getOneAddresses(address_id: int):
    # 查询所有用户地址
    address = await UserAddress.get(id=address_id)
    return {
        "code": 200,
        "message": "查询成功",
        "data": address
    }


class UserAddressIn(BaseModel):
    recipient_name:str # 收件人
    phone:str  # 手机号
    province:str  # 省
    city:str  # 市
    county:str  # 区
    detail_address:str  # 详细地址
    is_default:bool = False # 是否默认

    @validator('phone')
    def validate_phone(cls, v):
        if not v.isdigit():
            raise ValueError('手机号必须为数字')
        if len(v) != 11:
            raise ValueError('手机号必须为11位')
        return v
class UserAddressOut(BaseModel):
    id: int
    recipient_name: str
    phone: str
    province: str
    city: str
    county: str
    detail_address: str
    is_default: bool
    user_id: int # 输出模型仍然包含user_id用于显示
    created_at: datetime

    class Config:
        from_attributes = True


# 获取当前用户ID的依赖函数（需要根据你的认证系统实现）
# async def get_current_user_id(x_user_id: str = Header(...)):
#     """
#     从请求头获取用户ID
#     """
#     if not x_user_id:
#         raise HTTPException(status_code=401, detail="未认证")
#     return int(x_user_id)
# user_id: int = Depends(get_current_user_id)
@userAddress_api.post("/",summary="添加用户地址")
async def addUserAddress(address_data: UserAddressIn,current_user: User = Depends(get_current_user)):
    # 如果设置为默认地址，先取消该用户的其他默认地址
    user_id = current_user.id
    if address_data.is_default:
        await UserAddress.filter(user_id=address_data.user_id, is_default=True).update(is_default=False)
    # address_data_dict = address_data.dict()
    # # address_data_dict["user"] = id  # 这里添加用户ID
    address = await UserAddress.create(
        recipient_name=address_data.recipient_name,
        phone=address_data.phone,
        province=address_data.province,
        city=address_data.city,
        county=address_data.county,
        detail_address=address_data.detail_address,
        is_default=address_data.is_default,
        user_id=user_id

    )
    return {
        "code": 200,
        "message": "添加成功",
        "data": address  # 返回创建的对象
    }


@userAddress_api.delete("/{id}",summary="删除用户地址")
async def deleteUserAddress(id:int):
    address = await UserAddress.get_or_none(id=id)
    if not address:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="地址不存在"
        )

    # 不能删除默认地址
    if address.is_default:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能删除默认地址，请先设置其他地址为默认"
        )

    await address.delete()

    return {
        "code": 200,
        "message": "删除成功"
    }


@userAddress_api.put("/{id}", summary="修改用户地址")
async def updateUserAddress(
            id: int,
            address_data: UserAddressIn,
    ):

        # 3. 如果设置为默认地址，先取消该用户的其他默认地址
        if address_data.is_default:
            await UserAddress.filter(user_id=address_data.user_id, is_default=True).update(is_default=False)

        # 4. 更新数据（排除只读字段）
        address_dict= address_data.dict(exclude_unset=True)

        # 5. 执行更新
        await UserAddress.filter(id=id).update(**address_dict)
        # 6. 返回更新后的地址
        updated_address = await UserAddress.get(id=id)
        return {
            "code": 200,
            "message": "修改成功",
            "data": updated_address
        }